<template>
	<view>

		<view>
			<cu-custom :isBack="true">
				<block slot="backText"></block>
				<block slot="content">序列号打印</block>
			</cu-custom>
		</view>
		
		<view class="cu-bar bg-white search  indexes" >
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input @confirm="confirm" v-model="cbarcode" type="text" placeholder="请先聚焦后扫描条形码" :focus="focus"></input>
			</view>
			<view class="action" @click="toScan">
				<text class="cuIcon-scan" style="font-size: 56rpx;"></text>
			</view>
		</view>
		<view style="background-color: #FFFFFF;margin-top: 10px;">

			<view style="text-align: center;padding: 20rpx;" v-if="deviceList.length">
				已配对蓝牙设备
			</view>
			<view
				style="padding: 20rpx;border-radius: 15rpx;margin:10px;"
				:style="{'border':!device.check?'1rpx solid #aaa':'1rpx solid #00aa00',
				'color':!device.check?'#aaa':'#00aa00'}"
				class="uni-flex uni-row" v-for="(device,index) in deviceList" :key="index"
				@click="xuanzhe(device)">
				<view >{{index+1}}.</view>
				<view>
					<text style="display: inline-block;width: 100rpx;">NAME：</text> 
				{{device.name}}</view>
				<view>
					<text style="display: inline-block;width: 100rpx;">ADD：</text> 
				{{device.address}}</view>
				<!-- <view class="flex-item"><button type="primary" plain size="mini"
						@click="printSomething(device,printTest)">打印</button></view> -->
			</view>
			<!-- <u-empty v-if="!deviceList.length" text="没有搜索到蓝牙设备" mode="data"></u-empty> -->
			<view style="text-align: center;padding: 50px;" v-if="!deviceList.length">
				没有搜索到已配对蓝牙设备
			</view>
			<view style="text-align: center;margin-top: 20rpx;padding: 10px;">
				<button @click="initPrinter()" type="primary">
					刷新蓝牙设备
				</button>
			</view>
		</view>
	</view>

</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		// props: {
		// 	subdata: {
		// 		typeof: Object,
		// 		default: {
		// 			BarRk: {},
		// 			BarCk: {}

		// 		},
		// 		require: true
		// 	},
		// },
		data() {
			return {
				focus:true,
				cbarcode: '',
				printData:'',
				show: {
					setting: false
				},
				deviceList: [],
			}
		},
		onLoad(p) {
			// var that = this;

			// // #ifdef APP-PLUS
			// that.initPrinter();
			// // #endif
		},
		mounted() {
			var that = this;
			// #ifdef APP-PLUS
			that.initPrinter();
			// #endif
		},
		computed: {
			...mapState([ 'userInfo']),
		},

		methods: {
			xuanzhe(item){
				this.deviceList.forEach(i=>{
					if(i.address == item.address){
						i.check = true
					}else{
						i.check = false
					}
				})
				this.$forceUpdate();
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.cbarcode = ''
					this.focus = true; //  第二个输入框获取焦点。
				},500)
			},
			confirm(){
				let that = this
				if(this.deviceList.length){
					let data2 = {}
					this.deviceList.forEach(item=>{
						if(item.check){
							data2 = item
						}
					})
					this.printData = this.cbarcode
					this.focus = false; // 初始化 第二个输入框focus 属性
					setTimeout(() => {
						this.cbarcode = ''
						this.focus = true; //  第二个输入框获取焦点。
					},1000)
					
					uni.request({
						url: this.serverURL_a + `/barcode/decode/checkBarCode`,
						data: {
							barCode: this.printData,
							__sid: this.userInfo.sessionid,
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						},
						method: 'POST',
						success: function(data) {
							let res = data.data
							if(res.result == 'true'){
								console.log(this.printData,'printData===');
								this.printSomething(data2,this.printTest)
							}else{
								console.log('444444===');
								this.$api.msg("请扫描正确的条形码!");
								this.printData = ''
							}
						}.bind(this),
						fail: function() {
							this.$api.msg('无法连接服务，请联系管理');
							this.printData = ''
							return;
						}.bind(this),
					})
					
				}else{
					this.focus = false; // 初始化 第二个输入框focus 属性
					setTimeout(() => {
						this.cbarcode = ''
						this.focus = true; //  第二个输入框获取焦点。
					},1000)
					this.$api.msg("请先配对蓝牙!");
				}
				
			},
			/** 扫码*/
			toScan(){
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						var rdata = res.result;
						this.cbarcode = rdata;
						setTimeout(function(){
							this.confirm();
						}.bind(this),100);
					}.bind(this)
				});
			},
			showPrinterList: function() {
				var that = this;
				that.show.setting = true;
				for (var i = 0; i < that.deviceList.length; i++) {
					if (that.deviceList[i].name == that.device.name) {
						that.deviceList[i].checked = true
					}
				}
			},
			initPrinter: function() {
				var that = this;
				that.deviceList = [];
				var main = plus.android.runtimeMainActivity();
				var Context = plus.android.importClass("android.content.Context");
				var BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
				plus.android.importClass(BManager);
				var BAdapter = BManager.getAdapter();
				plus.android.importClass(BAdapter);
				var lists = BAdapter.getBondedDevices();
				plus.android.importClass(lists);
				var iterator = lists.iterator();
				plus.android.importClass(iterator);
				while (iterator.hasNext()) {
					var d = iterator.next();
					plus.android.importClass(d);
					var temp = {
						name: d.getName(),
						address: d.getAddress(),
						status: d.getBondState(),
						uuids: d.getUuids(),
						op: d
					};
					that.deviceList.push(temp);
				}
				if(that.deviceList.length){
					that.deviceList[0].check = true
					this.$forceUpdate();
				}
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.cbarcode = ''
					this.focus = true; //  第二个输入框获取焦点。
				},500)
				console.log(that.deviceList,'that.deviceList==');
			},
			printSomething: function(dev, sb) {
				var that = this;
				var main = plus.android.runtimeMainActivity();
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var UUID = plus.android.importClass("java.util.UUID");
				var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
				var BAdapter = BluetoothAdapter.getDefaultAdapter();
				var device = BAdapter.getRemoteDevice(dev.address);
				plus.android.importClass(device);
				var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
				plus.android.importClass(bluetoothSocket);
				console.log("开始连接打印机:" + dev.name);
				if (!bluetoothSocket.isConnected()) {
					bluetoothSocket.connect();
					if (bluetoothSocket.isConnected()) {
						console.log("设备已连接,开始发送打印文件");
						var outputStream = bluetoothSocket.getOutputStream();
						plus.android.importClass(outputStream);
						sb(outputStream);
						bluetoothSocket.close();
						if (!bluetoothSocket.isConnected()) {
							console.log("设备已关闭");
						}
					} else {
						uni.showToast({
							title: '设备连接失败',
							icon: 'error',
							duration: 2000
						});
					}
				}
				this.focus = false; 
				setTimeout(() => {
					this.focus = true; //  第二个输入框获取焦点。
				},500)
				this.printData = ''
			},
			printTest: function(outputStream) {
				console.log(this.printData,'this.printData==');
				var that = this;
				// 100  70
				// 75  130
				// 30   20
				// var text = "! 0 480 360 378 1\r\n";
				var text = "! 0 320 160 180 1\r\n";
				text += "SPEED 1\r\n"; //打印速度 0 到 5 
				
				
				// text += "CENTER\r\n"; //居中 介绍点位置 
				text += `BARCODE 128 1 0 60 0 20 ${that.printData}\r\n`;
				// text += "TEXT 7 0 210 60 HORIZ\r\n";
				
				// text += "CENTER\r\n"; //居中 介绍点位置
				text += "SETBOLD 0\r\n"; //加粗 1加粗0不加粗
				text += "SETMAG 1 1\r\n"; //放大 宽度 高度  1-16
				text += `T 3 2 40 90 ${that.printData}\r\n`;
				text += "SETMAG 0 0\r\n";
				text += "SETBOLD 0\r\n";


				text += "SETMAG 0 0\r\n";
				text += "SETBOLD 0\r\n";
				text += "FORM\r\n";
				text += "END\r\n";
				text += "PRINT\r\n"
				// console.log(text)
				var arrayBuffer = plus.android.invoke(text, 'getBytes', 'gbk');
				outputStream.write(arrayBuffer);
				outputStream.flush();

			},

			printBox: function(p, l, w, k, s) { //起点坐标、长高、宽、线宽、显示(上左下右)
				var text = "";
				if (s.t) {
					text = text.concat("L ", p.x, " ", p.y, " ", w, " ", p.y, " ", k, "\r\n");
				}
				if (s.l) {
					text = text.concat("L ", p.x, " ", p.y, " ", p.x, " ", p.y + l, " ", k, "\r\n");
				}
				if (s.b) {
					text = text.concat("L ", p.x, " ", p.y + l, " ", w, " ", p.y + l, " ", k, "\r\n");
				}
				if (s.r) {
					text = text.concat("L ", w, " ", p.y + l, " ", w, " ", p.y, " ", k, "\r\n");
				}
				return text;
			},
			cutLine: function(p, str) {
				var r = "";
				var max = 18;
				var n = parseInt(str.length / max);
				for (var i = 0; i < n; i++) {
					var temp = str.substr(i * max, max);
					r += "T 3 0 " + p.x + " " + (p.y + 40 * i) + " " + temp + "\r\n"
				}
				var w = str.substr(n * max);
				r += "T 3 0 " + p.x + " " + (p.y + 40 * n) + " " + w + "\r\n";
				return r;
			},
			printLineList: function(p, list) {
				var r = "";
				for (var i = 0; i < list.length && i < 5; i++) {
					r += "T 3 0 " + p.x + " " + (p.y + 40 * i) + " " + list[i] + "\r\n"
				}
				return r;
			},
			printLineList2: function(p, list) {
				var r = "";
				for (var i = 0; i < list.length && i < 10; i = i + 2) {
					r += "T 3 0 " + p.x + " " + (p.y + 60 * i) + " " + list[i] + "\r\n";
					if ((i + 1) < list.length) {
						r += "T 3 0 " + (p.x + 150) + " " + (p.y + 60 * i) + " " + list[i + 1] + "\r\n";
					}
				}
				return r;
			},
			mySleep: async function(time) {
				await this.mypromise(time);
			},
			mypromise: function(time) {
				return new Promise((resolve) => setTimeout(resolve, time));
			}
		}
	}
</script>

<style scoped>
	page {
		padding: 0;
		margin: 0;
	}

	.picked {
		background-color: lavender;
	}
</style>